#include "queue.h"

 queue queue_init(void) {
	queue q = (queue)malloc(sizeof(struct cque));
	q->cqsize = 0;
	q->toq = NULL;
	q->boq = NULL;
	return(q);
 }

 void  queue_push(queue q, void* value, size_t size) {
	qentry* item = (qentry*)malloc(sizeof(qentry));
	item->data = (size == 0) ? (int*)value : memcpy(malloc(size),value,size);
        if( q->cqsize == 0 ) {
		q->toq = q->boq = item;
	} else {
		q->boq->next = item;
		item->next = NULL;
		q->boq = item;
	}
	q->cqsize++;
	return;
 }

 void* queue_pop(queue q) { 
	void* item = NULL;
	if(q->cqsize == 0) return item;
	if(q->cqsize == 1) {
		item = q->toq->data;
		q->toq = NULL;
		q->boq = NULL;
		return item;
	}
	item = q->toq->data;
	q->toq = q->toq->next;
	q->cqsize--;
	return item; 
 }

 void  queue_destroy(queue q) {
	qentry* item = q->toq;
	qentry* temp;
	while(item != NULL) {
		temp = item;
		free(item->data);
		item = item->next;
		free(temp);
	}
	free(q);
 }

 void  queue_print(queue q) {
	qentry* item = q->toq;
	printf("[ ");
	while(item != NULL) {
		printf("%x ",(int)item->data);
		item = item->next;
	}
        printf("]\n");
 }

